import psutil
import time

process_field = [
    "pid",  # 进程ID
    "name",  # 进程名称
    "cpu_percent",  # 进程CPU利用率
    "memory_percent",  # 进程内存利用率
    "memory_info",  # 进程内存信息
    "status",  # 进程状态
    "create_time",  # 进程创建时间
    "cpu_times",  # 进程CPU时间信息
    "num_ctx_switches",  # 进程上下文切换信息
    "open_files",  # 进程打开的文件
    "num_threads",  # 进程线程数
]

# 获取所有进程
all_process_info = list(psutil.process_iter(process_field))

# 第一次调用cpu_percent()进行初始化
for proc in all_process_info:
    proc.cpu_percent()

# 等待一个短时间间隔
time.sleep(0.1)

# 第二次调用获取实际的CPU占用率
for proc in all_process_info:
    try:
        print(
            f'pid:{proc.info["pid"]} name:{proc.info["name"]} cpu:{proc.cpu_percent()} mem:{proc.info["memory_percent"]}'
        )
    except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
        continue
